<?php

    ini_set('display_errors', 'Off');

    $function = $_POST['function'];
    $reply = array();
    $time = time();

    // start session. reset if username expired.
    session_start();
    if (isset($_SESSION['last_activity']) && ($time - $_SESSION['last_activity'] > 120)) {
        session_unset();
        session_destroy();
        session_start();
    }

    // start mysql connection
    $db = new mysqli("127.0.0.1", "root", "12qwaszx", "webchat");
    if ($db->connect_errno) {
       die("Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error);
    }

    // update timestamps
    $_SESSION['last_activity'] = $time;
    if (isset($_SESSION['username'])) {
        $db->query("UPDATE users SET last_activity = $time WHERE username = '".$_SESSION['username']."';");
    }
    
    // main chat functions:
    switch($function) {
    
        /*
         * Gets called when a user starts the session to get the current
         * state of the chat.
         */
        case('getState'):
            if(file_exists('chat.txt')){
                $lines = file('chat.txt');
            }

            $reply['state'] = count($lines); 
            break;	
    	
        /*
         * Called to validate a users username. Deletes expired usernames, strips
         * all non numbers or letters, searches for conflicting usernames, returns
         * an appropriate response back to the user
         */
        case('validateUsername'):
            
            // delete all expired usernames
            $db->query("DELETE FROM users WHERE (username = '".$_SESSION['username'].
                       "' OR (username IS NOT NULL AND $time - last_activity > 120));");

            $username = preg_replace('/[^a-zA-Z0-9]/', '', $_POST['username']);
            $result = $db->query("SELECT * FROM users WHERE username = '$username';");

            // send response back to clients
            if ($result->num_rows != 0 || $username === '') {
                unset($_SESSION['username']);
                $reply['accepted'] = 'false';
            } else {
                $_SESSION['username'] = $username;
                $db->query("INSERT INTO users (username, last_activity) VALUES ('$username', $time);");
                $reply['accepted'] = 'true';
                $reply['username'] = $username;
            }

            break;

        /*
         * Called when a client wants to update to the latest state of the chat.
         */
        case('update'):

            $state = $_POST['state'];

            if(file_exists('chat.txt')) {
                $lines = file('chat.txt');
            }

            $count =  count($lines);
            if($state == $count) {
                $reply['state'] = $state;
                $reply['text'] = false;		 
            } else {
        	    $text= array();
        	    $reply['state'] = $state + count($lines) - $state;
        	    foreach ($lines as $line_num => $line) {
        		    if($line_num >= $state) {
                        $text[] =  $line = str_replace("\n", "", $line);
        		    }
                }
        	    $reply['text'] = $text; 
            }

            if (isset($_SESSION['username']))
                $reply['username'] = $_SESSION['username'];
            else
                $reply['username'] = "<none>";
        	  
            break;
    	 
        case('send'):      
            if (isset($_SESSION['username'])) {
                //$nickname = htmlentities(strip_tags($_POST['nickname']));
	            $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
	            $message = htmlentities(strip_tags($_POST['message']));
                if(($message) != "\n") {
        	
	                if(preg_match($reg_exUrl, $message, $url)) {
                        $message = preg_replace($reg_exUrl, '<a href="'.$url[0].'" target="_blank">'.$url[0].'</a>', $message);
	                } 
			 
                    fwrite(fopen('chat.txt', 'a'), 
                        '<div class="message-wrap"><div class="message"><div class="name-wrap"><span>'.$_SESSION['username'].
                        '</span></div><div class="message-body">'.str_replace("\n", " ", $message)."</div></div></div> \n"); 
                }
            } else {
                $reply['error'] = 'not_logged_in';
            }
            break;
    }
    
    // actually send back reply
    echo json_encode($reply);

?>